import pymysql, hashlib

def op_mysql(sql):
    mysql_info = {
        "host": "118.24.3.40",
        "user": "jxz",
        "password": "123456",
        "db": "jxz",
        "port": 3306,
        "charset": "utf8",
        "autocommit": True
    }
    conn = pymysql.connect(**mysql_info)
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute(sql)
    cur.close()
    conn.close()


def md5(s, salt='$!@#$12232'):
    s = (str(s) + salt).encode()
    m = hashlib.md5(s)  # 加密
    return m.hexdigest()


def register():  # 注册
    for i in range(3):
        username = input('username:').strip()
        password= input('password:').strip()
        cpasswd = input('cpassword:').strip()
        if username and password and cpasswd:
            if password== cpasswd:
                sql = "select * from mxl_user where username='%s';" % username
                if op_mysql(sql):
                    print('用户已经存在！')
                else:
                    md5_password = md5(password)
                    sql2 = 'insert into mxl_user (username,password) value ("%s","%s");' % (username, md5_password)
                    op_mysql(sql2)
                    print('注册成功！')
                    break
            else:
                print('两次密码输入不一致')
        else:
            print('账号/密码不能为空')


def login():  # 登录
    username = input('username:').strip()
    password = input('password:').strip()
    if username and password:
        sql = "select password from mxl_user where username = '%s';" % username
        res = op_mysql(sql)
        if res:
            new_passwd = md5(password)
            if res.get('password') == new_passwd:
                print('登录成功！')
            else:
                print('密码输入错误！')
        else:
            print('用户不存在')


if __name__ == '__main__':
   register()
   login()
